//
//  LTFTopicBaseHandel.m
//  NeteaseNews
//
//  Created by liutaifeng on 16/4/30.
//  Copyright © 2016年 liutaifeng. All rights reserved.
//

#import "LTFTopicBaseHandel.h"
#import "FMDB.h"
#import "LTFTopicModel.h"

@interface LTFTopicBaseHandel ()

@end

@implementation LTFTopicBaseHandel
//单例
+ (instancetype)shareDataBaseTool {
    static LTFTopicBaseHandel *handel = nil;
    static dispatch_once_t token;
    dispatch_once(&token, ^{
        handel = [[LTFTopicBaseHandel alloc] init];
        [handel openDB];
        [handel createTable];
    });
    return handel;
}
//打开数据库
- (void)openDB {
    NSString *sandBox = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *docPath = [sandBox stringByAppendingPathComponent:@"topic.sqlite"];
    NSLog(@"%@", docPath);
    int result = sqlite3_open([docPath UTF8String], &dbPoint);
    if (result == SQLITE_OK) {
        NSLog(@"打开成功");
    }
    else {
        NSLog(@"打开失败");
    }
}
//创建表格
- (void)createTable {
    NSString *sqlStr = @"create table if not exists topic (expertId text primary key)";
    int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"创建成功");
    }
    else {
        NSLog(@"创建失败: %d", result);
    }
}
//添加
- (void)insertModel:(NSString *)string {
    NSString *sqlStr = [NSString stringWithFormat:@"insert into topic (expertId) values('%@')", string];
    int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"添加成功");

    }
    else {
        NSLog(@"添加失败: %d", result);
    }
}
//查询
- (NSMutableArray *)select {
    // *号是通配符, 表示查询某个条件下, 数据库中所有字段内容
    NSString *selectSql = @"select * from topic";
    //创建一个跟随指针, 这个指针用来循环便利数据库中的每行代码.
    sqlite3_stmt *stmt = nil;
    int result = sqlite3_prepare_v2(dbPoint, [selectSql UTF8String], -1, &stmt, nil);
    NSMutableArray *topicArray = [NSMutableArray array];
    if (result == SQLITE_OK) {
        NSLog(@"查询成功");
        while (sqlite3_step(stmt) == SQLITE_ROW) {
            //如果跟随指针所指向的位置有一行, 则循环继续, 如果没有, 循环结束
            const unsigned char *expertId = sqlite3_column_text(stmt, 0);
            NSString *string = [NSString stringWithUTF8String:(const char*)expertId];
            [topicArray addObject:string];
        }
        
        return topicArray;
        
        
        
        
    }
    else {
        NSLog(@"查询错误: %d", result);
        return nil;
    }
    
}
//删除
- (void)deleteCollect:(NSString *)string {
    NSString *sqlStr = [NSString stringWithFormat:@"delete from topic where expertId = '%@'", string];
    int result = sqlite3_exec(dbPoint, [sqlStr UTF8String], nil, nil, nil);
    if (result == SQLITE_OK) {
        NSLog(@"删除成功");
    }
    else {
        NSLog(@"删除失败: %d", result);
    }
}



@end
